package com.hallowd.purcom;

import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;


public class SearchActivity extends Activity {
    private TextView myText = null;
    private static final String TAG = SearchActivity.class.getSimpleName();
    String searchedItem;
    ArrayList<String> communityList;
    ArrayList<String> descriptionList;
    ArrayList<String> communityIDList;
    ListView myList;
    Button homeButton;

    Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        Bundle extras = getIntent().getExtras();

        communityList = new ArrayList<String>();
        descriptionList = new ArrayList<String>();
        communityIDList = new ArrayList<String>();
        myList =(ListView) findViewById(R.id.communityList);
        searchedItem = "";
        activity = this;

        myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d("","clickedItem+ "+communityList.get(position));
                Log.d("","clickedItem+ "+descriptionList.get(position));
                Log.d("","clickedItem+ "+communityIDList.get(position));

                Intent myintent = new Intent(activity,showCommunityActivity.class);
                myintent.putExtra("communityName",communityList.get(position));
                myintent.putExtra("communityDescription",descriptionList.get(position));
                myintent.putExtra("communityID",communityIDList.get(position));
                startActivity(myintent);
            }
        });

        homeButton = (Button) findViewById(R.id.homeButton);
        homeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, wellcomePageActivity.class);
                startActivity(intent);
            }
        });

        if(extras!=null){
            searchedItem = extras.getString("searchedItem");
            myText = new TextView(this);
            myText.setText("Results for " +searchedItem);
        }


        // check if you are connected or not

        // call AsynTask to perform network operation on separate thread
        new HttpAsyncTask().execute("http://titan.cmpe.boun.edu.tr:8089/purcom/mobile/community/search");
    }


    public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {

            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            return GET(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Successful!", Toast.LENGTH_LONG).show();
            try {
                Log.d(TAG, "try a girdi.");

                JSONArray jArray = new JSONArray(result);
                Log.d(TAG, "2 a girdi."+searchedItem+searchedItem.length());

                Log.d(TAG,"lengthIs: "+jArray.length());
                communityList.clear();
                for (int i=0;i<jArray.length();++i){
                    if(jArray.getJSONObject(i).getString("name").toLowerCase().contains(searchedItem.toLowerCase()) == true) {
                        communityList.add(jArray.getJSONObject(i).getString("name"));
                        descriptionList.add(jArray.getJSONObject(i).getString("description"));
                        communityIDList.add(jArray.getJSONObject(i).getString("id"));
                    }
                }
                ArrayAdapter<String> myAdapter =  new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, communityList);

                myList.setAdapter(myAdapter);

            }catch (JSONException e) {

            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
